package com.xbzl.cly_demo.mqtt;

import com.xbzl.cly_demo.properties.MqttProperties;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttMsgCallback implements MqttCallbackExtended {
    @Autowired
    MqttProperties mqttProperties;

    MqttClient mqttClient;


    public void initMqttClient() throws MqttException {
        MqttConnectOptions options = new MqttConnectOptions();
        MqttClient client = new MqttClient(mqttProperties.getUrl(),mqttProperties.getClientId());
        client.setCallback(this);
        client.connect(options);
        this.mqttClient = client;
    }

    public void connectComplete(boolean reconnect, String serverUri) {
// 连接建立成功逻辑
// 此处一般需要实现主题订阅
    }

    @Override
    public void connectionLost(Throwable throwable) {

    }

    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // 接收到消息，根据需求完成消息处理逻辑： 解析，入库等
        String message = new String(mqttMessage.getPayload());
        System.out.println("topic:" + topic + ", payload:" + message);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}

